package cn.hl.hm.util;

import cn.hl.hm.entity.Order;
import com.vizhuo.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class OrderUtil { 
	private static Logger logger = Logger.getLogger(OrderUtil.class);
	private final static SimpleDateFormat shortSdf= new SimpleDateFormat("yyyyMMdd");
	private static AtomicInteger Atomic = new AtomicInteger();
	private static String HostIndex = null;
	private static String Pattern =    "000";
	private static int MAX_DAY_NUMBER = 1000;
	private static java.text.DecimalFormat df = new java.text.DecimalFormat(Pattern); 
	private static java.text.DecimalFormat ipdf = new java.text.DecimalFormat("000"); 
	private static String processId = ""; 
	private static OrderUtil instance = null; 
	public static synchronized OrderUtil getInstance() throws Exception {
		if (instance == null) {
			instance = new OrderUtil();
			init();
		}
		return instance;
	} 
	/**
	 * 
	 * @throws Exception
	 */
	private static void init() throws Exception {
		if (HostIndex == null) {
			HostIndex = getIpLast();
			HostIndex = ipdf.format(Integer.parseInt(HostIndex));
		}
		if (HostIndex == null) {
			throw new Exception(" HostIndex is 0");
		} 
		processId =  getProcessId();
		if(processId != null){
			processId = processId.substring(processId.length()-2,processId.length());
		} 
	}
	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	public  String getOrderCode() { 
		synchronized(this) {
			return String.valueOf(getDateStr() + HostIndex  + processId  + df.format(getNextValue() % MAX_DAY_NUMBER));
		}
	}
	
	public  String getRoadFeeOrderCode() { 
		String nanoTime = System.nanoTime()+"";
		String substring = nanoTime.toString().substring(7, 12);
		synchronized(this) {
			String valueOf = String.valueOf(getFixLenthString(3)+substring);
			System.out.println("【订单号】   "+valueOf);
			return valueOf;
		}
	}
	
	private static String getFixLenthString(int strLength) {  
	      
	    Random rm = new Random();  
	      
	    // 获得随机数  
	    double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);  
	  
	    // 将获得的获得随机数转化为字符串  
	    String fixLenthString = String.valueOf(pross);  
	  
	    // 返回固定的长度的随机数  
	    return fixLenthString.substring(1, strLength + 1);  
	} 
	/**
	 * 
	 * @param args
	 * @throws Exception
	 */
	
	/**
	 * 下个进程id
	 * 
	 * @return
	 */
	private static int getNextValue() {
		return Atomic.incrementAndGet();
	}

	/**
	 * 获得进程id
	 * 
	 * @return
	 */
	private static String getProcessId() {
		// get name representing the running Java virtual machine.
		String name = ManagementFactory.getRuntimeMXBean().getName();
		// get pid
		String pid = name.split("@")[0];
		return pid;
	} 
	private static String getIpLast() {
		String ip = getIp();
		System.out.println(ip);
		if (ip != null) {
			//
			String[] ipStrs = ip.split("\\."); 
			return ipStrs[3];
		}
		return null;
	}
 
	/**
	 * 
	 * @return
	 */
	private static String getIp() { 
		String ip = "";
		try {
			 List<InetAddress>  list = IPUtil.getAllHostAddress();
			 //
			 for(InetAddress address : list ){
				 ip = address.getHostAddress();
			 }
			return ip;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 1412241450
	 * 
	 * @return
	 */
	private static String getDateStr() {
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmm");// HHmmss
		return formatter.format(date).toString();
	}
	private static String getDateStr2() {
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("mmss");// HHmmss
		return formatter.format(date).toString();
	}
	/**
	 * 20140520
	 * 
	 * @return
	 */
	private static String getDateString() {
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		return formatter.format(date).toString();
	}
    //计算开始地址和结束地址计算总路程
	public static double  getDistinct(String startAddress,String endAddress){ 
		try{
			String srcUrl = "http://api.map.baidu.com/direction/v1?mode=driving&origin="+startAddress+"&destination="+endAddress+"&origin_region=%E4%B9%8C%E9%B2%81%E6%9C%A8%E9%BD%90&destination_region=%E4%B9%8C%E9%B2%81%E6%9C%A8%E9%BD%90&output=json&ak=PcszfTgVH4wxzyYIyiiVoBwBzlnWQLIT";
			NetRsp rsp = NetUtil.netInput(srcUrl, "UTF-8");
			if(rsp != null && rsp.getStatusCode() == 200){
				//"distance": 4218,
				int pos = rsp.getContent().indexOf("\"distance\":");
				if(pos != -1){
					String dis = rsp.getContent().substring(pos + "\"distance\":".length());
					pos = dis.indexOf(",");
					if(pos != -1){
						return Double.parseDouble(dis.substring(0,pos).trim());
					}
				}  
			} 
		}catch(Exception ioe){
			ioe.printStackTrace();
		}
		return 0;
	}
	/**
	  * @Title: checkSendParam  
	  * @Description: 校验必填项
	  * 所属物流公司／货物名称／货物数量／特殊需求 非必填
	  *	后台帮人下单，记录一下这个用户是不是注册用户吧，如果是注册用户这个通过后台下的单也要在那个用户的账号下记录，且所属物流公司自动就填上了
	  * @date: 2017年1月4日
	  * @author: 大和
	  * @param order
	  * @return boolean 
	  * @throws
	 */
	public static boolean checkSendParam(Order order){
		if(StringUtil.isBlank(order.getSenderPhone())){
			return false;
		}else if (order.getCarId()==null) {
			return false;
		}
//		else if (order.getCarLineId()==null) {
//			return false;
//		}
		else if (StringUtils.isBlank(order.getLineName())) {
			return false;
		}else if (StringUtils.isBlank(order.getTotalPriceStr())) {
			return false;
		}else if (StringUtils.isBlank(order.getDestAddress())) {
			return false;
		}else if (StringUtils.isBlank(order.getSrcAddress())) {
			return false;
		}
		else if (order.getLineId()==null) {
			return false;
		}else if (order.getUseTime()==null) {
			return false;
		}else if (StringUtil.isBlank(order.getReciveverPhone())) {
			return false;
		}else if (StringUtil.isBlank(order.getUserAccount())) {
			return false;
		}else{
			return true;
		}
	}

}
